package com.angle.fastgo.product.handler;

import com.angle.fastgo.common.enums.BizCodeEnums;
import com.angle.fastgo.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description: 全局异常处理器
 * version: 1.0
 * date: 2020/11/21 16:58
 * author: zhuwei
 */
@RestControllerAdvice
@Slf4j
public class FastGoExceptionHandler {


    /**
     * description: TODO
     * version: 1.0
     * date: 2020/11/21 17:08
     * author: zhuwei
     * @param e MethodArgumentNotValidException参数校验异常
     * @return R
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R MethodArgumentNotValidException(MethodArgumentNotValidException e ) {
        log.error("数据校验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,Object> errFiledMap = new HashMap<>();
        List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
        fieldErrorList.stream().forEach(fieldError -> {
            String errorFileName = fieldError.getField();
            String errorMsg = fieldError.getDefaultMessage();
            errFiledMap.put(errorFileName,errorMsg);
        });
        return R.error(BizCodeEnums.SYSTEM_UNKNOW_ERROR).put("data",errFiledMap);
    }


    /**
     * description: 处理系统级别未知错误的异常
     * version: 1.0
     * date: 2020/11/21 17:00
     * author: zhuwei
     * @param throwable 异常信息
     * @return R
     */
    @ExceptionHandler(value = Throwable.class)
    public R handlerException(Throwable throwable) {
        log.error("系统未知错误:{}",throwable);
        return R.error(BizCodeEnums.SYSTEM_UNKNOW_ERROR.getCode(),BizCodeEnums.SYSTEM_UNKNOW_ERROR.getMsg());
    }
}
